package top.suyarong.ftbqsync.timer;

import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import top.suyarong.ftbqsync.data.entity.FtbQuestSync;
import top.suyarong.ftbqsync.utils.AstralSorceryUtil;
import top.suyarong.ftbqsync.utils.FTBQuestUtil;
import top.suyarong.ftbqsync.utils.LogUtil;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定时任务,将玩家数据应用到服务器
 */
public class DataSyncTask extends BukkitRunnable {

    public static final ConcurrentHashMap<Player, FtbQuestSync> taskMap = new ConcurrentHashMap<>(64);
    public static final ConcurrentHashMap<String, Player> lock = new ConcurrentHashMap<>(64);

    private static final LogUtil log = LogUtil.getInstance();

    @Override
    public void run() {
        if (taskMap.size() <= 0) return;
        Iterator<Map.Entry<Player, FtbQuestSync>> iterator = taskMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Player, FtbQuestSync> entry = iterator.next();
            Player player = entry.getKey();
            FtbQuestSync ftbQuestSync = entry.getValue();

            if (!player.isOnline()) continue;

            dataCopy(player, ftbQuestSync);
            iterator.remove();
        }

    }

    private void dataCopy(Player player, FtbQuestSync ftbQuestSync) {
        String playerName = player.getName();

        sql2ServerData(player, ftbQuestSync);
        lock.remove(playerName);
        log.message(player, "&e&l任务数据同步完成");
    }

    // 数据库任务数据写入当前服务器
    private void sql2ServerData(Player player, FtbQuestSync ftbQuestSync) {
        byte[] ftbData = ftbQuestSync.getFtbData();
        byte[] astralData = ftbQuestSync.getAstralData();
        if (!player.isOnline()) return;
        FTBQuestUtil.setPlayerQuest(player, ftbData);
        AstralSorceryUtil.setPlayerAstral(player, astralData);
    }

    public static boolean isLock(String playerName) {
        return Objects.nonNull(DataSyncTask.lock.get(playerName));
    }
}
